import { LoginRes, TokenRes, RolesPerms } from "../api/auth/types";

// 本地存储
class LocalStorage {

  // 用户租户
  getUserTenant(): string {
    return "xyvcard";
  }

  // 组织租户
  getOrganTenant(): string {
    return "sooyie";
  }

  getToken(): string {
    return wx.getStorageSync("token");
  }

  getRefreshToken(): string {
    return wx.getStorageSync("refreshToken");
  }

  getRoleCodes(): Array<string> {
    return wx.getStorageSync("roleCodes");
  }

  getPermCodes(): Array<string> {
    return wx.getStorageSync("permCodes");
  }

  // 获取Bearer 格式请求Token.
  getBearerToken(): string {
    return wx.getStorageSync("token") ? "Bearer " + wx.getStorageSync("token") : "";
  }

  //Token 是否过期.
  isTokenExpire(): boolean {
    if (wx.getStorageSync("token")) {
      const expireTime = wx.getStorageSync("expireTime");
      return (expireTime && new Date().getTime() > expireTime);
    }
    return false
  }

  // 登录存储Token等信息
  loginStorage(loginResp: LoginRes): void {
    if (loginResp.token) {
      this.tokenStorage(loginResp.token);
    }
    // 申请入会需要用到手机号
    wx.setStorageSync("mobilePhone", loginResp.message);
  }

  // Token存储
  tokenStorage(tokenRes: TokenRes): void {
    wx.setStorageSync("token", tokenRes.accessToken);
    wx.setStorageSync("expiresIn", tokenRes.expiresIn);
    wx.setStorageSync("refreshToken", tokenRes.refreshToken);
    if (tokenRes.expiresIn) {
      const expireTime = new Date().getTime() + tokenRes.expiresIn * 1000 - 60 * 1000;
      wx.setStorageSync("expireTime", expireTime);
    }
  }

  // 登录未注册
  unregisteredStorage(loginResp: LoginRes): void {
    wx.setStorageSync("cacheKey", loginResp.cacheKey);
  }

  // 角色权限存储
  rolesPermsStorage(rolesPerms: RolesPerms): void {
    wx.setStorageSync("roleCodes", rolesPerms.roleCodes);
    wx.setStorageSync("permCodes", rolesPerms.permCodes);
  }

}

const db = new LocalStorage();
export { db }